// 我的  页面接口
const express = require("express");
const route = express.Router();
const pool = require("../utils/mysql");
const Joi = require('joi')

// 用户修改个人信息
route.put('/me/update_myinfo', (req, res) => {
    let sql = 'update pet_user set u_name=?,u_phone=?,u_email=?,u_sex=? where u_id=?'
    let { u_name, u_phone, u_email, u_sex, u_id } = req.body
    console.log(req.body);

    let schema = Joi.object({
        u_name: Joi.string().required(), // 必填
        u_phone: Joi.string().required(), // 必填
        u_email: Joi.string().required(), // 必填
        u_sex: Joi.string().required(), // 必填
        u_id: Joi.string().required(), // 必填
    });
    let { error } = schema.validate(req.body);
    if (error) {
        res.send({ code: 401, err: error.details });
        return; // 结束
    }



    pool.query(sql, [u_name, u_phone, u_email, u_sex, u_id], (err, r) => {
        if (err) {
            res.send({ code: 500, msg: err })
        } else {
            res.send({ code: 200, msg: 'ok' })
        }
    })

})

// 修改头像
route.put('/me/update_avatar', (req, res) => {
    let { u_img, u_id } = req.body

    let schema = Joi.object({
        u_id: Joi.string().required(), // 必填
        u_img: Joi.string().required(), // 必填
    });
    let { error } = schema.validate(req.body);
    if (error) {
        res.send({ code: 401, err: error.details });
        return; // 结束
    }

    let sql = 'update pet_user set u_img=? where u_id=?'
    pool.query(sql, [u_img, u_id], (err, r) => {
        if (err) {
            res.send({ code: 500, msg: err })
        } else {
            res.send({ code: 200, msg: 'ok' })
        }
    })
})

// 用户修改密码
route.put('/me/update_pwd', (req, res) => {
    let { u_pwd, u_id } = req.body

    let schema = Joi.object({
        u_pwd: Joi.string().required(), // 必填
        u_id: Joi.string().required(), // 必填
    });
    let { error } = schema.validate(req.body);
    if (error) {
        res.send({ code: 401, err: error.details });
        return; // 结束
    }


    let sql = 'update pet_user set u_pwd=MD5(?) where u_id=?'
    pool.query(sql, [u_pwd, u_id], (err, r) => {
        if (err) {
            res.send({ code: 500, msg: err })
        } else {
            res.send({ code: 200, msg: 'ok' })
        }
    })
})
module.exports = route